using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Net;
using AAClicker;

namespace Utility.Internet
{
    public static class InternetUtility
    {
        internal static int _healthyTries = 3;
        public static void Reset() { 
            _healthyTries = 3;
            AAExceptionServiceUnreachable.ListExceptionsClear();
        }
        public static bool TestHealthyWebService()
        {
            if (_healthyTries++ > 7)
                throw new AAExceptionServiceUnreachable();

            bool result = true;
            string TestWebServiceURL = "http://beta.mso.bz/healthy.aspx";
            var getquery = string.Format("{0}?timestamp={1}", TestWebServiceURL, DateTime.Now.ToFileTimeUtc());

            WebProxy proxy = new WebProxy();
            proxy.Credentials = CredentialCache.DefaultCredentials;
            var request = WebRequest.Create(TestWebServiceURL);
            request.Proxy = proxy;
            request.Method = "GET";
            request.Timeout = ((_healthyTries + 1)/2 * 1000);     // 2sec, 2.5sec, 3sec, 3.5sec, 4sec, 4.5sec, 5sec

            try
            {
                var response = request.GetResponse();
                using (var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
                {

                    var responseresult = reader.ReadToEnd();
                    result = responseresult.Contains("MSO Service Healthy!");
                }

            }
            catch (WebException handled)
            {
                new AAExceptionServiceUnreachable(handled.Status, handled.Message);
                return false;
            }

            // sleep and try service again
            if(!result)
                System.Threading.Thread.Sleep(100);

            return result;
        }
    }
}
